package com.chensi.admin.userservice.service.impl;

import com.chensi.admin.userservice.dao.SuggestionPictureRepository;
import com.chensi.admin.userservice.service.SuggestionPictureService;
import com.google.common.collect.Lists;
import com.chensi.admin.userservice.common.Constants;
import com.chensi.admin.userservice.domain.SuggestionPicture;
import com.chensi.admin.userservice.domain.UserSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * @author si.chen
 * @date 2019/7/813:26
 */
@Service
public class SuggestionPictureServiceImpl implements SuggestionPictureService {

    private final SuggestionPictureRepository suggestionPictureRepository;

    @Autowired
    public SuggestionPictureServiceImpl(SuggestionPictureRepository suggestionPictureRepository) {
        this.suggestionPictureRepository = suggestionPictureRepository;
    }

    @Override
    public List<SuggestionPicture> get(UserSuggestion userSuggestion) {
        return suggestionPictureRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = getPredicates(root, cb);
            predicates.add(cb.equal(root.get("userSuggestion"), userSuggestion));
            query.where(predicates.toArray(new Predicate[0]));
            return query.getRestriction();
        });
    }

    private List<Predicate> getPredicates(Root<SuggestionPicture> root, CriteriaBuilder cb) {
        Predicate predicate = cb.equal(root.get("deleted"), Constants.DELETED_NO);
        return Lists.newArrayList(predicate);
    }
}
